package com.lagou.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import java.util.List;
import java.util.concurrent.Callable;

/**
 *  自定义事件处理器
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    //1.定义成员变量
    private ChannelHandlerContext context; // 事件处理器上下文对象 (存储handler信息,写操作)
    private String result; // 记录服务器返回的数据
    private String param; // 记录将要返送给服务器的数据
    private String server;
    private static String path = "/server";
    //2.实现channelActive  客户端和服务器连接时,该方法就自动执行
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 初始化ChannelHandlerContext
        this.context = ctx;
    }


    //3.实现channelRead 当我们读到服务器数据,该方法自动执行
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将读到的服务器的数据msg ,设置为成员变量的值
        result = msg.toString();
        notify();
    }

    //4.将客户端的数写到服务器
    public synchronized Object call() {
        //context给服务器写数据
        context.writeAndFlush(param);
        long curTime = System.currentTimeMillis();
        try {
            wait(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(System.currentTimeMillis()-curTime>10000){
            System.out.println("wait response time out");
            result = "fail";
        } else {
            try {
                updateZookeeper(this.server);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //5.设置参数的方法
    public void setParam(String param){
        this.param = param;
    }

    public void setServer(String server) {
        this.server = server;
    }

    private void updateZookeeper(String server) throws Exception {
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 1);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("rpc")  // 独立的命名空间 /base
                .build();

        client.start();

        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path+"/"+server);
        if(System.currentTimeMillis()-stat.getMtime()>5000){
            System.out.println("last update time >5s");
            client.setData().forPath(path+"/"+server,"".getBytes());
        } else {
            System.out.println("last update time <=5s");
            client.setData().forPath(path+"/"+server, Long.toString(System.currentTimeMillis()).getBytes());
        }
    }
}
